package com.witframework.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Properties;

import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import com.witframework.WitException;


public class PropertiesUtil {	
	public static Properties loadProperties(String resourceName){
		try {
			return loadProperties(resourceName,null);
		} catch (IOException e) {
			throw new WitException(e);
		}
	}
	public static Properties loadProperties(String resourceName, ClassLoader classLoader) throws IOException {
		Assert.notNull(resourceName, "Resource name must not be null");
		ClassLoader clToUse = classLoader;
		if (clToUse == null) {
			clToUse = ClassUtils.getDefaultClassLoader();
		}
		Properties properties = new Properties();
		Enumeration urls = clToUse.getResources(resourceName);
		while (urls.hasMoreElements()) {
			URL url = (URL) urls.nextElement();
			InputStream is = null;
			try {
				URLConnection con = url.openConnection();
				con.setUseCaches(false);
				is = con.getInputStream();				
				properties.load(is);
			}catch(Exception e){
				throw new WitException("decrypt file error",e);
			}
			finally {
				if (is != null) {
					is.close();
				}
			}
		}
		return properties;
	}
}
